import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

const initialForm = {
  team: "",
  warehouseName: "",
  waybillNumber: "",
  outboundOrderNumber: "",
  creationTime: "",
  skuType: "",
  skuQuantity: "",
  weight: "",
  length: "",
  width: "",
  height: "",
  recipient: "",
  recipientPhoneNumber: "",
  attachment: "",
  states: "未发货"
};

const teamOptions = ["A团队", "B团队", "C团队"];
const warehouseOptions = ["上海仓", "北京仓", "深圳仓"];
const skuTypeOptions = ["电子产品", "服装", "食品"];

// 现代化渐变背景
const pageBg: React.CSSProperties = {
  minHeight: '100vh',
  background: 'linear-gradient(120deg, #e0f7fa 0%, #f8fafc 100%)',
  padding: '48px 0',
  fontFamily: 'Segoe UI, Roboto, Arial',
};
// 卡片样式
const formStyle: React.CSSProperties = {
  maxWidth: 520,
  margin: "0 auto",
  background: "#fff",
  borderRadius: 24,
  boxShadow: "0 8px 32px 0 rgba(0,0,0,0.12)",
  padding: 40,
  transition: 'box-shadow 0.3s',
  position: "relative"
};
// 渐变大标题+图标
const titleStyle: React.CSSProperties = {
  textAlign: 'center' as const,
  marginBottom: 36,
  fontSize: 30,
  fontWeight: 800,
  background: "linear-gradient(90deg, #00b388 0%, #1890ff 100%)",
  WebkitBackgroundClip: "text",
  WebkitTextFillColor: "transparent",
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 12
};
// 分组
const groupStyle = { display: "flex", gap: 32, marginBottom: 0 };
const groupItemStyle = { flex: 1 };
// 标签
const labelStyle = { display: "block", marginBottom: 10, fontWeight: 500, color: "#333", fontSize: 16 };
// 输入框
const inputStyle: React.CSSProperties = {
  width: "100%",
  padding: "12px 14px",
  borderRadius: 14,
  border: "1.5px solid #e0e0e0",
  marginBottom: 26,
  fontSize: 17,
  outline: "none",
  transition: "border-color 0.2s, box-shadow 0.2s",
  background: '#f8fafc',
  boxSizing: 'border-box' as const
};
// 按钮
const btnStyle: React.CSSProperties = {
  padding: "14px 40px",
  background: 'linear-gradient(90deg, #00b388 0%, #1890ff 100%)',
  color: "#fff",
  border: "none",
  borderRadius: 24,
  fontSize: 18,
  fontWeight: 600,
  cursor: "pointer",
  marginRight: 18,
  boxShadow: "0 2px 12px #00b38833",
  transition: "background 0.2s, box-shadow 0.2s"
};
const btnHoverStyle: React.CSSProperties = {
  background: 'linear-gradient(90deg, #009970 0%, #1769aa 100%)',
  boxShadow: "0 4px 24px #1890ff33"
};
const resetBtnStyle: React.CSSProperties = {
  ...btnStyle,
  background: "#f5f5f5",
  color: "#333",
  boxShadow: "none"
};
const msgStyle = (success: boolean) => ({
  marginTop: 28,
  color: success ? "#00b388" : "#ff4d4f",
  textAlign: 'center' as const,
  fontWeight: 700,
  fontSize: 18,
  letterSpacing: 1
});

const CreatePendingShipmentWaybills = () => {
  const [form, setForm] = useState(initialForm);
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState("");
  const [btnHover, setBtnHover] = useState(false);
  const [cardHover, setCardHover] = useState(false);
  const navigate = useNavigate();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
  };

  const handleRadioChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm(prev => ({ ...prev, states: e.target.value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMsg("");
    try {
      const payload = {
        Team: form.team,
        WarehouseName: form.warehouseName,
        WaybillNumber: form.waybillNumber,
        OutboundOrderNumber: form.outboundOrderNumber,
        CreationTime: form.creationTime,
        SKUType: form.skuType,
        SKUQuantity: form.skuQuantity,
        Weight: Number(form.weight),
        Length: Number(form.length),
        Width: Number(form.width),
        Height: Number(form.height),
        Recipient: form.recipient,
        RecipientPhoneNumber: form.recipientPhoneNumber,
        Attachment: form.attachment,
        States: form.states
      };
      const res = await axios.post("http://localhost:5017/api/PendingShipmentWaybills/CreatePendingShipmentWaybills", payload);
      if (res.data && res.data.code === 200) {
        setMsg("添加成功！");
        setForm(initialForm);
        setTimeout(() => {
          navigate("/Layout/ShowPendingShipmentWaybills");
        }, 800);
      } else {
        setMsg(res.data?.msg || "添加失败");
      }
    } catch (err: any) {
      setMsg("请求失败: " + (err.response?.data?.msg || err.message));
    }
    setLoading(false);
  };

  const handleReset = () => {
    setForm(initialForm);
    setMsg("");
  };

  // 响应式样式
  const responsiveFormStyle = {
    ...formStyle,
    width: "97%",
    minWidth: 0,
    boxSizing: 'border-box' as const,
    boxShadow: cardHover ? '0 16px 48px 0 rgba(24,144,255,0.18)' : formStyle.boxShadow
  };

  return (
    <div style={pageBg}>
      <form
        style={responsiveFormStyle}
        onSubmit={handleSubmit}
        onMouseEnter={() => setCardHover(true)}
        onMouseLeave={() => setCardHover(false)}
      >
        <div style={titleStyle}>
          <span role="img" aria-label="add" style={{fontSize: 32}}>🚚</span>
          添加待发货运单
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>团队
              <select
                style={inputStyle}
                name="team"
                value={form.team}
                onChange={handleChange}
                required
              >
                <option value="" disabled>请选择团队</option>
                {teamOptions.map(opt => <option key={opt} value={opt}>{opt}</option>)}
              </select>
            </label>
          </div>
          <div style={groupItemStyle}>
            <label style={labelStyle}>仓库名称
              <select
                style={inputStyle}
                name="warehouseName"
                value={form.warehouseName}
                onChange={handleChange}
                required
              >
                <option value="" disabled>请选择仓库</option>
                {warehouseOptions.map(opt => <option key={opt} value={opt}>{opt}</option>)}
              </select>
            </label>
          </div>
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>运单号 <input style={inputStyle} name="waybillNumber" value={form.waybillNumber} onChange={handleChange} required /></label>
          </div>
          <div style={groupItemStyle}>
            <label style={labelStyle}>出货单号 <input style={inputStyle} name="outboundOrderNumber" value={form.outboundOrderNumber} onChange={handleChange} required /></label>
          </div>
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>创建时间
              <input
                style={inputStyle}
                name="creationTime"
                value={form.creationTime}
                onChange={handleChange}
                required
                type="datetime-local"
              />
            </label>
          </div>
          <div style={groupItemStyle}>
            <label style={labelStyle}>SKU种类
              <select
                style={inputStyle}
                name="skuType"
                value={form.skuType}
                onChange={handleChange}
                required
              >
                <option value="" disabled>请选择SKU种类</option>
                {skuTypeOptions.map(opt => <option key={opt} value={opt}>{opt}</option>)}
              </select>
            </label>
          </div>
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>SKU数量 <input style={inputStyle} name="skuQuantity" value={form.skuQuantity} onChange={handleChange} required /></label>
          </div>
          <div style={groupItemStyle}>
            <label style={labelStyle}>重量(KG) <input style={inputStyle} name="weight" value={form.weight} onChange={handleChange} required type="number" min="0" step="0.01" /></label>
          </div>
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>长(CM) <input style={inputStyle} name="length" value={form.length} onChange={handleChange} required type="number" min="0" step="0.01" /></label>
          </div>
          <div style={groupItemStyle}>
            <label style={labelStyle}>宽(CM) <input style={inputStyle} name="width" value={form.width} onChange={handleChange} required type="number" min="0" step="0.01" /></label>
          </div>
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>高(CM) <input style={inputStyle} name="height" value={form.height} onChange={handleChange} required type="number" min="0" step="0.01" /></label>
          </div>
          <div style={groupItemStyle}>
            <label style={labelStyle}>收件人 <input style={inputStyle} name="recipient" value={form.recipient} onChange={handleChange} required /></label>
          </div>
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>收件电话 <input style={inputStyle} name="recipientPhoneNumber" value={form.recipientPhoneNumber} onChange={handleChange} required /></label>
          </div>
          <div style={groupItemStyle}>
            <label style={labelStyle}>附件 <input style={inputStyle} name="attachment" value={form.attachment} onChange={handleChange} required /></label>
          </div>
        </div>
        <div style={groupStyle}>
          <div style={groupItemStyle}>
            <label style={labelStyle}>状态</label>
            <div style={{ display: 'flex', gap: 24, marginBottom: 26 }}>
              <label style={{ fontWeight: 500, fontSize: 16 }}>
                <input
                  type="radio"
                  name="states"
                  value="未发货"
                  checked={form.states === "未发货"}
                  onChange={handleRadioChange}
                  style={{ marginRight: 6 }}
                />
                未发货
              </label>
              <label style={{ fontWeight: 500, fontSize: 16 }}>
                <input
                  type="radio"
                  name="states"
                  value="已发货"
                  checked={form.states === "已发货"}
                  onChange={handleRadioChange}
                  style={{ marginRight: 6 }}
                />
                已发货
              </label>
            </div>
          </div>
        </div>
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <button
            type="submit"
            style={btnHover ? { ...btnStyle, ...btnHoverStyle } : btnStyle}
            disabled={loading}
            onMouseEnter={() => setBtnHover(true)}
            onMouseLeave={() => setBtnHover(false)}
          >
            {loading ? "提交中..." : "提交"}
          </button>
          <button type="button" style={resetBtnStyle} onClick={handleReset}>重置</button>
          <button 
            type="button" 
            style={{
              ...resetBtnStyle,
              marginLeft: 18,
              background: "#ff4d4f",
              color: "#fff"
            }} 
            onClick={() => navigate("/Layout/ShowPendingShipmentWaybills")}
          >
            返回
          </button>
        </div>
        {msg && <div style={msgStyle(msg.includes("成功"))}>{msg}</div>}
      </form>
    </div>
  );
};

export default CreatePendingShipmentWaybills;
